package com.ibm.risk.irmp.base.auth.service.impl;//package com.ibm.riskmeasure.rwaservice.service.usermng.impl;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.Optional;
//
//import jakarta.persistence.EntityManager;
//
//import org.apache.commons.lang3.StringUtils;
//import jakarta.persistence.Query;
////import org.hibernate.query.internal.NativeQueryImpl;
//import org.hibernate.transform.Transformers;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Example;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.multipart.MultipartFile;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.google.common.collect.ImmutableMap;
////.common.ServiceRuntimeException;
////.common.cache.ICacheService;
////.common.utils.BeanListUtils;
////.dao.SystemGroupDataRepository;
////.dao.SystemGroupRepository;
////.dao.SystemGroupRoleRepository;
////.dao.SystemGroupUserRepository;
////.dao.SystemUserRepository;
////.entity.PBatchEntity;
////.entity.PSystemGroupDataEntity;
////.entity.PSystemGroupEntity;
////.entity.PSystemGroupRoleEntity;
////.service.dataquery.IFreeTableQueryService;
////.service.usermng.IGroupManagementService;
//
//@Service
//public class GroupManagementServiceImpl implements IGroupManagementService {
//    private static final Logger log = LoggerFactory.getLogger(GroupManagementServiceImpl.class);
//    @Autowired
//    EntityManager entityManager;
//
//    @Autowired
//    SystemUserRepository systemUserRepository;
//
//    @Autowired
//    SystemGroupUserRepository systemGroupUserRepository;
//
//    @Autowired
//    SystemGroupRoleRepository systemGroupRoleRepository;
//
//    @Autowired
//    SystemGroupDataRepository systemGroupDataRepository;
//
//    @Autowired
//    SystemGroupRepository systemGroupRepository;
//
//    @Autowired
//    IFreeTableQueryService freeTableQueryService;
//
//    @Autowired
//    ICacheService cacheService;
//
//    @Transactional
//    @Override
//    public JSONObject showUser(String groupCode, Integer pageIndex, Integer pageSize) {
////        String groupCode = jsonObject.getString("groupCode");
//
////        List<PSystemGroupUserEntity> groupUserList = systemGroupUserRepository.findByGroupId(groupCode);
////        List<Long> userIdList = new ArrayList<>();
////        for (PSystemGroupUserEntity entity: groupUserList) {
////            userIdList.add(entity.getUserId());
////        }
////
////        int count = 0;
////        if(userIdList.size() > 0) {
////            count = systemUserRepository.countDistinctByUserIdIn(userIdList);
////        }
////        int pageSize = 20;
////        int pageIndex = 1;
////        if (jsonObject.getJSONObject("page") != null &&
////                jsonObject.getJSONObject("page").getInteger("pageSize") != null) {
////            pageSize = jsonObject.getJSONObject("page").getInteger("pageSize");
////        }
////        if (jsonObject.getJSONObject("page") != null &&
////                jsonObject.getJSONObject("page").getInteger("pageIndex") != null) {
////            pageIndex = jsonObject.getJSONObject("page").getInteger("pageIndex");
////        }
////
////        Pageable pageable = PageRequest.of(pageIndex - 1, pageSize, Sort.Direction.ASC, "USER_ID");
////        List<Map<String, String>> resultList = new ArrayList<>();
////        if(userIdList.size() > 0) {
////            resultList = systemUserRepository.findAllByUserIdIn(userIdList, pageable);
////        }
////
////        JSONObject result = new JSONObject();
////        result.put("total", count);
////        result.put("list", resultList);
//        String sql = "SELECT u.USER_ID, u.USER_EMAIL, u.USER_REALNAME, u.USER_NAME, u.USER_SERIAL_NUM, u.USER_STATUS\n" +
//                "  FROM RI_BASE_AUTH_USER u INNER JOIN RI_BASE_AUTH_GROUP_USER gu ON u.USER_ID = gu.USER_ID \n" +
//                "  WHERE gu.GROUP_ID = :groupCode";
//        Map<String, Object> params = new HashMap<String, Object>(){{
//            put("groupCode", groupCode);
//        }};
//        JSONObject resultList = freeTableQueryService.pagedQueryWithCount(sql, pageIndex, pageSize, params);
//        return resultList;
//    }
//
//
//    @Transactional
//    @Override
//    public JSONObject showEditGroup(String groupCode, Integer pageIndex, Integer pageSize) {
//
//        String sql = "SELECT NODE_ID, PARENT_ID, GROUP_CODE, IS_VIRTUAL, GROUP_TYPE, GROUP_NAME, GROUP_LEVEL, GROUP_STATUS, "
//        		+ "CREATE_DATE, IS_CONFLIG" +
//                "  FROM RI_BASE_AUTH_GROUP  WHERE GROUP_CODE = :groupCode";
//        Map<String, Object> params = new HashMap<String, Object>(){{
//            put("groupCode", groupCode);
//        }};
//        JSONObject resultList = freeTableQueryService.pagedQueryWithCount(sql, pageIndex, pageSize, params);
//        return resultList;
//    }
//
//    @Override
//    @Transactional
//    public boolean deleteByGroupCode(String groupCode) throws Exception {
//
//		//SELECT * FROM RI_BASE_AUTH_GROUP WHERE node_id = '04825'
//		//SELECT * FROM RI_BASE_AUTH_GROUP_DATA WHERE group_id = '04825'
//		//SELECT * FROM RI_BASE_AUTH_GROUP_ROLE WHERE group_id = '04825'
//		//SELECT * FROM RI_BASE_AUTH_GROUP_USER WHERE group_id = '04825'
//		//删除RI_BASE_AUTH_GROUP数据
//        String sql1 = "delete from RI_BASE_AUTH_GROUP where group_code = '" + groupCode + "'" ;
//        Query query1 = entityManager.createNativeQuery(sql1);
//        query1.executeUpdate();
//
//		//删除RI_BASE_AUTH_GROUP_DATA数据
//        String sql2 = "delete from RI_BASE_AUTH_GROUP_DATA where group_id = '" + groupCode + "'" ;
//        Query query2 = entityManager.createNativeQuery(sql2);
//        query2.executeUpdate();
//
//		//删除RI_BASE_AUTH_GROUP_ROLE数据
//        String sql3 = "delete from RI_BASE_AUTH_GROUP_ROLE where group_id = '" + groupCode + "'" ;
//        Query query3 = entityManager.createNativeQuery(sql3);
//        query3.executeUpdate();
//
//		//删除RI_BASE_AUTH_GROUP_USER数据
//        String sql4 = "delete from RI_BASE_AUTH_GROUP_USER where group_id = '" + groupCode + "'" ;
//        Query query4 = entityManager.createNativeQuery(sql4);
//        query4.executeUpdate();
//
//        String cacheKey = "system_group_cachekey_" + PSystemGroupEntity.ENUM_GROUP_TYPE.USER_BRANCH.getCode();
//        cacheService.remove(cacheKey);
//
//        return true;
//    }
//
//
//    @Override
//    public List<String> showRoleSelected(String Group_ID) {
//        PSystemGroupRoleEntity grouproleEntity = new PSystemGroupRoleEntity();
//        grouproleEntity.setGroupId(Group_ID);
//        List<PSystemGroupRoleEntity> findList = systemGroupRoleRepository.findAll(Example.of(grouproleEntity));
//        List<String> resultList = new ArrayList<>();
//        for (int i = 0; i < findList.size(); i++) {
//            resultList.add(findList.get(i).getRoleId());
//        }
//        return resultList;
//    }
//
//    @Override
//    public List<String> showDataSelected(String Group_ID) {
//        PSystemGroupDataEntity groupdataEntity = new PSystemGroupDataEntity();
//        groupdataEntity.setGroupId(Group_ID);
//        List<PSystemGroupDataEntity> findList = systemGroupDataRepository.findAll(Example.of(groupdataEntity));
//        List<String> resultList = new ArrayList<>();
//        for (int i = 0; i < findList.size(); i++) {
//            resultList.add(findList.get(i).getBizBranchCode());
//        }
//        return resultList;
//    }
//
//    @Override
//    @Transactional
//    public Boolean editRole(String groupId, List<String> roleIds) {
//        if(roleIds == null) {
//            roleIds = new ArrayList<>();
//        }
//
//        //读取数据库中现有记录
//        PSystemGroupRoleEntity groupRoleEntity = new PSystemGroupRoleEntity();
//        groupRoleEntity.setGroupId(groupId);
//        List<PSystemGroupRoleEntity> savedGroupRoles = systemGroupRoleRepository.findAll(Example.of(groupRoleEntity));
//
//        List<String> savedRoleIds = new ArrayList<>();
//        for(PSystemGroupRoleEntity entity : savedGroupRoles) {
//            if(roleIds.contains(entity.getRoleId())) {
//                //保持不变
//                savedRoleIds.add(entity.getRoleId());
//            } else {
//                //删除
//                systemGroupRoleRepository.deleteById(entity.getGroupRoleId());
//            }
//        };
//
//        //新增加数据记录
//        roleIds.forEach(x -> {
//            if(!savedRoleIds.contains(x)) {
//                //新增加记录
//                PSystemGroupRoleEntity entity = new PSystemGroupRoleEntity();
//                entity.setGroupId(groupId);
//                entity.setRoleId(x);
//                systemGroupRoleRepository.save(entity);
//            }
//        });
//        return true;
////        try {
////            this.deleteRole(Group_ID);
////            if (jsonArray.size() == 0) {
////                return true;
////            } else {
////                List<PSystemGrouproleEntity> list = jsonArray.toJavaList(PSystemGrouproleEntity.class);
////                list = systemGrouproleRepository.saveAll(list);
////                if (jsonArray.size() == list.size()) {
////                    return true;
////                }
////            }
////            return false;
////        } catch (Exception ex) {
////            ex.printStackTrace();
////            return false;
////        }
//    }
//
//    @Override
//    @Transactional
//    public Boolean editData(String groupId, List<String> branchCodes) {
//        if(branchCodes == null) {
//            branchCodes = new ArrayList<>();
//        }
//
//        //读取数据库中现有记录
//        PSystemGroupDataEntity groupDataEntity = new PSystemGroupDataEntity();
//        groupDataEntity.setGroupId(groupId);
//        List<PSystemGroupDataEntity> savedGroupRoles = systemGroupDataRepository.findAll(Example.of(groupDataEntity));
//
//        List<String> savedBranchCodes = new ArrayList<>();
//        for(PSystemGroupDataEntity entity : savedGroupRoles) {
//            if(branchCodes.contains(entity.getBizBranchCode())) {
//                //保持不变
//                savedBranchCodes.add(entity.getBizBranchCode());
//            } else {
//                //删除
//                systemGroupDataRepository.deleteById(entity.getGroupDataId());
//            }
//        };
//
//        //新增加数据记录
//        branchCodes.forEach(x -> {
//            if(!savedBranchCodes.contains(x)) {
//                //新增加记录
//                PSystemGroupDataEntity entity = new PSystemGroupDataEntity();
//                entity.setGroupId(groupId);
//                entity.setFinBranchCode(x);
//                systemGroupDataRepository.save(entity);
//            }
//        });
//        return true;
////        try {
////            this.deleteData(Group_ID);
////            if (jsonArray.size() == 0) {
////                return true;
////            } else {
////                List<PSystemGroupdataEntity> list = jsonArray.toJavaList(PSystemGroupdataEntity.class);
////                list = middlewareGroupdataRepository.saveAll(list);
////                if (jsonArray.size() == list.size()) {
////                    return true;
////                }
////            }
////            return false;
////        } catch (Exception ex) {
////            ex.printStackTrace();
////            return false;
////        }
//    }
//
////    @Override
////    public void deleteRole(String Group_ID) {
////        PSystemGroupRoleEntity grouproleEntity = new PSystemGroupRoleEntity();
////        grouproleEntity.setGroupId(Group_ID);
////        List<PSystemGroupRoleEntity> findList = systemGroupRoleRepository
////                .findAll(Example.of(grouproleEntity));
////        systemGroupRoleRepository.deleteInBatch(findList);
////    }
//
////    @Override
////    public void deleteData(String Group_ID) {
////        PSystemGroupDataEntity groupdataEntity = new PSystemGroupDataEntity();
////        groupdataEntity.setGroupId(Group_ID);
////        List<PSystemGroupDataEntity> findList = systemGroupDataRepository
////                .findAll(Example.of(groupdataEntity));
////        systemGroupDataRepository.deleteInBatch(findList);
////    }
//
//    @Override
//    public JSONArray showGroup(String groupType) {
//        String cacheKey = "system_group_cachekey_" + groupType;
//        JSONArray groupTree = (JSONArray) cacheService.get(cacheKey);
//        if(groupTree != null && groupTree.size() > 0) {
//            return groupTree;
//        }
////        PSystemGroupEntity groupEntity = new PSystemGroupEntity();
////        groupEntity.setGroupType(GROUP_TYPE);
////        groupEntity.setIsConflig(IS_CONFLIG);
////        List<PSystemGroupEntity> list = systemGroupRepository.findAll(Example.of(groupEntity));
////                Sort.by(Sort.Direction.ASC, "groupCode"));
//        String sql = "SELECT t.NODE_ID, t.PARENT_ID, t.GROUP_NAME, t.GROUP_LEVEL FROM RI_BASE_AUTH_GROUP t" +
//                " where t.GROUP_TYPE = :groupType order by t.NODE_ID";  //t.GROUP_LEVEL <= 1 and
//        Query query = entityManager.createNativeQuery(sql);
//        List<Map<String,Object>> resultList = query.setParameter("groupType", groupType)
//
//                //.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
//                .getResultList();
////        JSONArray groupList = (JSONArray) JSONArray.toJSON(list);
//
////        JSONArray treeArray = new JSONArray();
////        JSONObject treeMap = new JSONObject();
////        Iterator<Object> it = groupList.iterator();
//        /*JSONObject childrenMap = new JSONObject();
//        while (it.hasNext()) {
//            JSONObject group = JSONObject.parseObject(it.next().toString());
//            //是否存在父亲节点
//            if (group.get("PARENT_ID") != null && !group.getString("PARENT_ID").trim().isEmpty()) {
//                //存在，说明是子节点,写入到孩子节点
//                String parent_id = group.getString("PARENT_ID");
//                //判定父亲列表是否存在，不存在，创建
//                JSONObject node = new JSONObject();
//                JSONObject child = new JSONObject();
//                JSONArray children = new JSONArray();
//                if (treeMap.get(parent_id) != null) {
//                    //存在父亲节点，取父亲节点
//                    node = treeMap.getJSONObject(parent_id);
//                    if (node.get("children") != null) {
//                        //存在孩子列表
//                        children = node.getJSONArray("children");
//                    }
//                }
//                child.put("title", group.get("GROUP_NAME"));
//                if(PSystemGroupEntity.ENUM_GROUP_TYPE.FIN_BRANCH.getCode().equals(GROUP_TYPE)) {
//                    child.put("key", String.valueOf(group.get("GROUP_CODE")));
//                    child.put("value", String.valueOf(group.get("GROUP_CODE")));
//                } else {
//                    child.put("key", String.valueOf(group.get("NODE_ID")));
//                    child.put("value", String.valueOf(group.get("NODE_ID")));
//                }
//                child.put("obj", group);
//                child.put("isLeaf", true);
//                children.add(child);
//                node.put("children", children);
//                node.put("isLeaf", false);
//                childrenMap.put(group.getString("NODE_ID"), child);
//                treeMap.put(parent_id, node);
//            } else {
//                //不存在父亲节点，说明是Root，创建NODE_ID的根
//                String parent_id = group.getString("NODE_ID");
//                JSONObject node = new JSONObject();
//                if (treeMap.get(parent_id) != null) {
//                    //判定有没有先前创建，有创建
//                    node = treeMap.getJSONObject(parent_id);
//                    if (node.get("children") != null) {
//                        //判定有没有孩子
//                        node.put("isLeaf", false);
//                    } else {
//                        //无孩子
//                        node.put("isLeaf", true);
//                    }
//                } else {
//                    //没创建，无孩子
//                    node.put("isLeaf", true);
//                }
//                //更新基本信息
//                node.put("title", group.get("GROUP_NAME"));
//                if(PSystemGroupEntity.ENUM_GROUP_TYPE.FIN_BRANCH.getCode().equals(GROUP_TYPE)) {
//                    node.put("key", String.valueOf(group.get("GROUP_CODE")));
//                    node.put("value", String.valueOf(group.get("GROUP_CODE")));
//                } else {
//                    node.put("key", String.valueOf(group.get("NODE_ID")));
//                    node.put("value", String.valueOf(group.get("NODE_ID")));
//                }
//                node.put("obj", group);
//
//                treeMap.put(parent_id, node);
//            }
//        }
////        System.out.println(treeMap.toJSONString());
//        for (String node_id : treeMap.keySet()) {
//            JSONObject node = treeMap.getJSONObject(node_id);
//            //处理即是Parent又是Children的情况并完善treeArray
//            JSONObject child = childrenMap.getJSONObject(node_id);
//            if (node.getJSONArray("children") != null) {
//                //node.getJSONArray("children").sort(Comparator.comparing(obj -> ((JSONObject) obj).getLong("key")));
//            }
//            if (child != null) {
//                child.put("isLeaf", false);
//                child.put("children", node.getJSONArray("children"));
//            } else {
//                treeArray.add(node);
//            }
//        }*/
//        //treeArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getLong("key")));
//        groupTree = buildDataTree(resultList, null);
//        cacheService.put(cacheKey, groupTree);
//        return groupTree;
//    }
//
//    @Transactional
//    @Override
//    public boolean save(PSystemGroupEntity entity) {
//        if(entity == null) {
//            return false;
//        }
//
//    	systemGroupRepository.save(entity);
//
//        return true;
//    }
//
//    @Override
//	public PSystemGroupEntity getGroupInfo(String nodeId) {
//        Optional<PSystemGroupEntity> entity = systemGroupRepository.findById(nodeId);
//        if(entity.isPresent() == false) {
//            throw new ServiceRuntimeException(501, "指定的用户组未找到");
//        }
//        return entity.get();
//    }
//
//
//    private JSONArray buildDataTree(List<Map<String, Object>> dataList, String pid) {
//        //树形目录下拉框
//        JSONArray params = new JSONArray();
//        for (Map<String, Object> paramItem : dataList) {
//            if(StringUtils.equals(pid, (String)paramItem.get("PARENT_ID"))) {
//                JSONObject item = new JSONObject();
//                item.put("title", paramItem.get("GROUP_NAME") + "(" + paramItem.get("NODE_ID") + ")");
//                item.put("value", paramItem.get("NODE_ID"));
//                item.put("key", paramItem.get("NODE_ID"));
//
////                if(pid == null || "1".equals(String.valueOf(paramItem.get("GROUP_LEVEL")))) {
//                if(pid == null) {
//                    item.put("expanded", true);
//                }
//                JSONArray children = buildDataTree(dataList, (String)paramItem.get("NODE_ID"));
//                if(children.size() == 0) {
//                    item.put("isLeaf", true);
//                } else {
//                    item.put("isLeaf", false);
//                }
//                item.put("children", children);
//                params.add(item);
//            }
//        }
//        return params;
//    }
//
//    /**
//     * 账务机构(仅读取一级机构)
//     */
//    public List<Map<String, Object>> getLevel1FinBranch(String consFlag) {
//        String sql = "SELECT t.id, t.fin_branch_code, t.fin_branch_name, t.belong_level \n" +
//                "  FROM RI_BASE_AUTH_FIN_BRANCH t\n" +
//                "  WHERE t.cons_flag = :consFlag\n" +
//                "  ORDER BY t.belong_level, t.fin_branch_code ";  //seq_num
//        Map<String, Object> params = BeanListUtils.castMapFrom("consFlag", consFlag);
//        List<Map<String, Object>> resultList = freeTableQueryService.pagedQuery(sql, 0, 999, params);
//        return resultList;
//    }
//}
